// 定义表格模板的接口
export interface TableTemplate {
  id: string;
  name: string;
  description: string;
  category: 'resume' | 'schedule' | 'finance' | 'custom' | 'community';
  thumbnail: string; // 缩略图URL或Base64
  createdBy?: string; // 创建者，用于社区模板
  createdAt: number; // 时间戳
  data: {
    rows: number;
    cols: number;
    cells: {
      rowSpan: number;
      colSpan: number;
      content: string;
      style: {
        fontWeight: string;
        fontStyle: string;
        textDecoration: string;
        textAlign: string;
        backgroundColor: string;
        color: string;
        borderWidth: string;
        borderColor: string;
        borderStyle: string;
        padding: string;
      };
    }[][];
  };
}

// 预设模板数据
export const predefinedTemplates: TableTemplate[] = [
  {
    id: 'resume-simple',
    name: '简约简历模板',
    description: '适合求职的简洁简历表格模板',
    category: 'resume',
    thumbnail: '',
    createdAt: Date.now(),
    data: {
      rows: 6,
      cols: 2,
      cells: Array(6).fill(0).map((_, rowIndex) => 
        Array(2).fill(0).map((_, colIndex) => {
          // 根据位置设置不同的内容和样式
          let content = '';
          let rowSpan = 1;
          let colSpan = 1;
          
          if (rowIndex === 0 && colIndex === 0) {
            content = '姓名';
          } else if (rowIndex === 0 && colIndex === 1) {
            content = '张三';
          } else if (rowIndex === 1 && colIndex === 0) {
            content = '学历';
          } else if (rowIndex === 1 && colIndex === 1) {
            content = '本科';
          } else if (rowIndex === 2 && colIndex === 0) {
            content = '专业';
          } else if (rowIndex === 2 && colIndex === 1) {
            content = '计算机科学与技术';
          } else if (rowIndex === 3 && colIndex === 0) {
            content = '工作经验';
          } else if (rowIndex === 3 && colIndex === 1) {
            content = '3年';
          } else if (rowIndex === 4 && colIndex === 0) {
            content = '技能';
          } else if (rowIndex === 4 && colIndex === 1) {
            content = 'React, JavaScript, TypeScript';
          } else if (rowIndex === 5 && colIndex === 0) {
            content = '自我评价';
            rowSpan = 1;
          } else if (rowIndex === 5 && colIndex === 1) {
            content = '热爱编程，责任心强，学习能力好';
            rowSpan = 1;
          }
          
          return {
            rowSpan,
            colSpan,
            content,
            style: {
              fontWeight: rowIndex === 0 && colIndex === 0 ? 'bold' : 'normal',
              fontStyle: 'normal',
              textDecoration: 'none',
              textAlign: colIndex === 0 ? 'right' : 'left',
              backgroundColor: colIndex === 0 ? '#f0f0f0' : 'white',
              color: '#000000',
              borderWidth: '1px',
              borderColor: '#d9d9d9',
              borderStyle: 'solid',
              padding: '8px'
            }
          };
        })
      )
    }
  },
  {
    id: 'schedule-weekly',
    name: '每周课程表',
    description: '周一至周五的课程安排表格',
    category: 'schedule',
    thumbnail: '',
    createdAt: Date.now(),
    data: {
      rows: 6,
      cols: 6,
      cells: Array(6).fill(0).map((_, rowIndex) => 
        Array(6).fill(0).map((_, colIndex) => {
          let content = '';
          
          if (rowIndex === 0 && colIndex === 0) {
            content = '时间/星期';
          } else if (rowIndex === 0) {
            content = ['一', '二', '三', '四', '五'][colIndex - 1];
          } else if (colIndex === 0) {
            content = `第${rowIndex}节`;
          }
          
          return {
            rowSpan: 1,
            colSpan: 1,
            content,
            style: {
              fontWeight: (rowIndex === 0 || colIndex === 0) ? 'bold' : 'normal',
              fontStyle: 'normal',
              textDecoration: 'none',
              textAlign: 'center',
              backgroundColor: (rowIndex === 0 || colIndex === 0) ? '#e6f7ff' : 'white',
              color: '#000000',
              borderWidth: '1px',
              borderColor: '#d9d9d9',
              borderStyle: 'solid',
              padding: '8px'
            }
          };
        })
      )
    }
  },
  {
    id: 'finance-report',
    name: '财务报表',
    description: '月度收支财务报表模板',
    category: 'finance',
    thumbnail: '',
    createdAt: Date.now(),
    data: {
      rows: 5,
      cols: 4,
      cells: Array(5).fill(0).map((_, rowIndex) => 
        Array(4).fill(0).map((_, colIndex) => {
          let content = '';
          
          if (rowIndex === 0 && colIndex === 0) {
            content = '项目';
          } else if (rowIndex === 0 && colIndex === 1) {
            content = '1月';
          } else if (rowIndex === 0 && colIndex === 2) {
            content = '2月';
          } else if (rowIndex === 0 && colIndex === 3) {
            content = '3月';
          } else if (rowIndex === 1 && colIndex === 0) {
            content = '收入';
          } else if (rowIndex === 2 && colIndex === 0) {
            content = '支出';
          } else if (rowIndex === 3 && colIndex === 0) {
            content = '结余';
          } else if (rowIndex === 4 && colIndex === 0) {
            content = '累计';
          }
          
          return {
            rowSpan: 1,
            colSpan: 1,
            content,
            style: {
              fontWeight: (rowIndex === 0 || colIndex === 0) ? 'bold' : 'normal',
              fontStyle: 'normal',
              textDecoration: 'none',
              textAlign: (rowIndex === 0 || colIndex === 0) ? 'center' : 'right',
              backgroundColor: rowIndex === 0 ? '#f5f5f5' : (colIndex === 0 ? '#fafafa' : 'white'),
              color: '#000000',
              borderWidth: '1px',
              borderColor: '#d9d9d9',
              borderStyle: 'solid',
              padding: '8px'
            }
          };
        })
      )
    }
  }
];

// 模拟社区模板数据
export const communityTemplates: TableTemplate[] = [
  {
    id: 'community-gantt',
    name: '项目甘特图',
    description: '社区分享的项目进度跟踪表',
    category: 'community',
    thumbnail: '',
    createdBy: '用户A',
    createdAt: Date.now() - 7 * 24 * 60 * 60 * 1000, // 7天前
    data: {
      rows: 5,
      cols: 6,
      cells: Array(5).fill(0).map((_, rowIndex) => 
        Array(6).fill(0).map((_, colIndex) => {
          let content = '';
          
          if (rowIndex === 0 && colIndex === 0) {
            content = '任务';
          } else if (rowIndex === 0) {
            content = ['第1周', '第2周', '第3周', '第4周', '第5周'][colIndex - 1];
          } else if (colIndex === 0) {
            content = [`任务${rowIndex}`, '需求分析', '设计', '开发', '测试'][rowIndex];
          }
          
          return {
            rowSpan: 1,
            colSpan: 1,
            content,
            style: {
              fontWeight: (rowIndex === 0 || colIndex === 0) ? 'bold' : 'normal',
              fontStyle: 'normal',
              textDecoration: 'none',
              textAlign: 'center',
              backgroundColor: (rowIndex === 0 || colIndex === 0) ? '#f0f0f0' : 'white',
              color: '#000000',
              borderWidth: '1px',
              borderColor: '#d9d9d9',
              borderStyle: 'solid',
              padding: '8px'
            }
          };
        })
      )
    }
  },
  {
    id: 'community-inventory',
    name: '库存管理表',
    description: '社区分享的产品库存管理模板',
    category: 'community',
    thumbnail: '',
    createdBy: '用户B',
    createdAt: Date.now() - 3 * 24 * 60 * 60 * 1000, // 3天前
    data: {
      rows: 4,
      cols: 5,
      cells: Array(4).fill(0).map((_, rowIndex) => 
        Array(5).fill(0).map((_, colIndex) => {
          let content = '';
          
          if (rowIndex === 0 && colIndex === 0) {
            content = '产品编号';
          } else if (rowIndex === 0 && colIndex === 1) {
            content = '产品名称';
          } else if (rowIndex === 0 && colIndex === 2) {
            content = '库存数量';
          } else if (rowIndex === 0 && colIndex === 3) {
            content = '单价';
          } else if (rowIndex === 0 && colIndex === 4) {
            content = '总价值';
          }
          
          return {
            rowSpan: 1,
            colSpan: 1,
            content,
            style: {
              fontWeight: rowIndex === 0 ? 'bold' : 'normal',
              fontStyle: 'normal',
              textDecoration: 'none',
              textAlign: rowIndex === 0 ? 'center' : 'left',
              backgroundColor: rowIndex === 0 ? '#e6f7ff' : (rowIndex % 2 === 0 ? '#fafafa' : 'white'),
              color: '#000000',
              borderWidth: '1px',
              borderColor: '#d9d9d9',
              borderStyle: 'solid',
              padding: '8px'
            }
          };
        })
      )
    }
  }
];

// 存储用户自定义模板
export const saveUserTemplate = (template: TableTemplate): void => {
  try {
    const existingTemplates = getUserTemplates();
    
    // 检查是否已存在相同ID的模板
    const index = existingTemplates.findIndex(t => t.id === template.id);
    if (index !== -1) {
      // 更新现有模板
      existingTemplates[index] = template;
    } else {
      // 添加新模板
      existingTemplates.push(template);
    }
    
    localStorage.setItem('userTemplates', JSON.stringify(existingTemplates));
  } catch (error) {
    console.error('保存模板失败:', error);
  }
};

// 获取用户自定义模板
export const getUserTemplates = (): TableTemplate[] => {
  try {
    const templatesJson = localStorage.getItem('userTemplates');
    return templatesJson ? JSON.parse(templatesJson) : [];
  } catch (error) {
    console.error('获取用户模板失败:', error);
    return [];
  }
};

// 删除用户模板
export const deleteUserTemplate = (templateId: string): void => {
  try {
    const existingTemplates = getUserTemplates();
    const filteredTemplates = existingTemplates.filter(template => template.id !== templateId);
    localStorage.setItem('userTemplates', JSON.stringify(filteredTemplates));
  } catch (error) {
    console.error('删除模板失败:', error);
  }
};

// 生成缩略图 (简化版，实际情况可能需要使用canvas或其他方式生成)
export const generateThumbnail = (): string => {
  // 这里返回一个简单的Base64编码的图片数据
  return '';
};

// 生成唯一ID
export const generateId = (): string => {
  return `template-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
}; 